#include "appglobal.h"
#include "appsetting.h"
#include "urlrecogniser.h"
#include "diskmap.h"
#include "downloadthread.h"
#include "entities.h"
#include <QNetworkAccessManager>
//#include <QWebView>
#include <QDebug>

YDAppGlobal g;

bool YDAppGlobal::initialize() {
    this->settings = new YDAppSettings(this);
    this->urlRecogniser = new YDUrlRecogniser(this);
    this->networkAccessMgr = new QNetworkAccessManager(this);
    //this->webView = new QWebView(nullptr);
    this->diskMap = new YDDiskMap(this);
    this->downloadThread = new YDDownloadThread(this);

    this->downloadThread->start();

    return true;
}

void YDAppGlobal::uninitialize() {
    this->downloadThread->exit();
    this->downloadThread->wait();

    delete this->diskMap;
    //delete this->webView;
    delete this->networkAccessMgr;
    delete this->urlRecogniser;
    delete this->settings;
}

#include <stdlib.h>
void YDAppGlobal::SplitPath(const QString& fullPath, QString& drive, QString& dir, QString& fileName, QString& ext) {
    int size = wcslen(reinterpret_cast<const wchar_t*>(fullPath.utf16())) + 1;
    wchar_t* wcsDrive = new wchar_t[size];
    wchar_t* wcsDir = new wchar_t[size];
    wchar_t* wcsFileName = new wchar_t[size];
    wchar_t* wcsExt = new wchar_t[size];

    _wsplitpath(reinterpret_cast<const wchar_t*>(fullPath.utf16()), wcsDrive, wcsDir, wcsFileName, wcsExt);

    drive.fromUtf16(reinterpret_cast<const ushort*>(wcsDrive));
    dir.fromUtf16(reinterpret_cast<const ushort*>(wcsDir));
    fileName.fromUtf16(reinterpret_cast<const ushort*>(wcsFileName));
    ext.fromUtf16(reinterpret_cast<const ushort*>(wcsExt));

    delete[] wcsDrive;
    delete[] wcsDir;
    delete[] wcsFileName;
    delete[] wcsExt;
}

QString YDAppGlobal::MakePath(const QString& drive, const QString& dir, const QString& fileName, const QString& ext) {
    wchar_t wcsPath[_MAX_PATH + 1];
    QString ret;

    _wmakepath(wcsPath,
        reinterpret_cast<const wchar_t*>(drive.utf16()),
        reinterpret_cast<const wchar_t*>(dir.utf16()),
        reinterpret_cast<const wchar_t*>(fileName.utf16()),
        reinterpret_cast<const wchar_t*>(ext.utf16()));
    ret.fromUtf16(reinterpret_cast<const ushort*>(wcsPath));

    return ret;
}

QString YDAppGlobal::unescape(const QString& src) {
    QByteArray u8Src = src.toUtf8();
    int len = strlen(u8Src.data());
    char* u8Dest = new char[len + 1];

    u8Dest[len] = '\0';
    qDebug() << u8Src;
    decode_html_entities_utf8(u8Dest, u8Src.data());
    qDebug() << u8Dest;

    return QString::fromUtf8(u8Dest);
}
